package com.meng.demo1.consistenthash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: menglinggang
 * @Date: 2020-07-08
 * @Time: 上午9:24
 */
public class HashAlgorithm implements IHashAlgorithm {

    private static MessageDigest md5Digest = null;

    static {
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 not supported", e);
        }
    }
    @Override
    public long hash(String k) {
        byte[] strBytes = computeMd5(k);
        long rv = ((long) (strBytes[3] & 0xFF) << 24)
                | ((long) (strBytes[2] & 0xFF) << 16)
                | ((long) (strBytes[1] & 0xFF) << 8)
                | (strBytes[0] & 0xFF);
        return rv & 0xffffffffL;
    }

    /**
     * Get the md5 of the given key.
     */
    public static byte[] computeMd5(String k) {
        MessageDigest md5;
        try {
            md5 = (MessageDigest) md5Digest.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException("clone of MD5 not supported", e);
        }
        md5.update(k.getBytes());
        return md5.digest();
    }

}
